package com.yanqu.road.server.manager.activity.langyabang;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.langyabang.entity.LangYaTypePatrons;
import com.yanqu.road.entity.activity.langyabang.entity.LangYaUserPatronsInfo;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.player.UserPatrons;
import com.yanqu.road.entity.rank.yrank.UnionYRank;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroup;
import com.yanqu.road.logic.bussiness.servercenter.ActivityBussiness;
import com.yanqu.road.logic.pb.UnionBasePb;
import com.yanqu.road.pb.activity.LangYaBangProto;
import com.yanqu.road.pb.cross.activity.CrossActivityProto;
import com.yanqu.road.server.CrossBaseServer;
import com.yanqu.road.server.TempCrossMgr;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.manager.union.activitygroup.Cross2UnionActivityGroupMgr;
import com.yanqu.road.server.manager.yrank.CrossYRankMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.date.DateHelper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CrossLangYaBangMgr extends TempCrossMgr {

    private static Logger logger = LogManager.getLogger(LangYaBangActivity.class.getName());
    //活动id 分组 活动
    public static Map<Integer,CrossLangYaBangActivityGroup> activityMap = new ConcurrentHashMap<>();

    @Override
    public boolean reloadConfig() throws Exception {
        CrossLangYaBangConfigMgr.reloadConfig();
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        getLogger().info("start reload LangYaBang activity  start");
        // 获取活动
        String nowTimeStr = DateHelper.getCurrentDateTimeString();
        List<Integer> activityTypeList = new ArrayList<>();
        activityTypeList.add(eActivityType.LangYaBang.getValue());

        Map<Integer, ActivityInfo> activityInfoMap = ActivityBussiness.getOpenCrossRankActivityInfoMap(activityTypeList, nowTimeStr);
        long serverId = CrossBaseServer.getInstance().getServerId();

        // 重新加载数据
        for (ActivityInfo activityInfo : activityInfoMap.values()) {
            //拿出分组
            Map<Integer, UnionActivityGroup> groupMap = Cross2UnionActivityGroupMgr.getGroupMap(activityInfo.getActivityId());
            //分组不为空
            if (groupMap != null) {
                //遍历分组
                for (Map.Entry<Integer, UnionActivityGroup> groupEntry : groupMap.entrySet()) {
                    UnionActivityGroup group = groupEntry.getValue();
                    //如果分组的跨服id等于当前服务器id
                    if (group.getCrossServerId() == serverId) {
                        getActivity(activityInfo.getActivityId(), group.getGroupId());
                    }
                }
            }
        }
        getLogger().info("start reload LangYaBang activity  end");
        return true;
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }


    @Override
    public boolean stop() {
        return false;
    }

    @Override
    public boolean save() {
        for (CrossLangYaBangActivityGroup crossLangYaBangActivityGroup:activityMap.values()){
            for (LangYaBangActivity activity:crossLangYaBangActivityGroup.getActivityMap().values()){
                activity.save();
            }
        }
        return true;
    }

    public static LangYaBangActivity getActivity(int activityId,int groupId){
        UnionActivityGroup group = Cross2UnionActivityGroupMgr.getGroupData(activityId,groupId);
        if (group == null){
            return null;
        }
        if (activityMap.get(activityId) == null){
            synchronized (activityMap){
                if (activityMap.get(activityId) == null){
                    ActivityInfo activityInfo = ActivityBussiness.getActivityInfoByActivityId(activityId);
                    if (activityInfo == null) {
                        return null;
                    }
                    CrossLangYaBangActivityGroup crossLangYaBangActivityGroup = new CrossLangYaBangActivityGroup(activityInfo);
                    activityMap.put(activityId,crossLangYaBangActivityGroup);
                }
            }
        }
        CrossLangYaBangActivityGroup crossLangYaBangActivityGroup = activityMap.get(activityId);
        return crossLangYaBangActivityGroup.getActivity(groupId);
    }

    public static LangYaBangProto.LangYaBangUserDataSyncRespMsg.Builder getUserSyncMsg(int activityId, long userId, int groupId, Map<Integer, LangYaTypePatrons> userPatronsInfos,long serverId){
        LangYaBangProto.LangYaBangUserDataSyncRespMsg.Builder builder = LangYaBangProto.LangYaBangUserDataSyncRespMsg.newBuilder();

        LangYaBangActivity activity = getActivity(activityId, groupId);
        if (activity == null){
            builder.setRet(GameErrorCode.E_LANG_YA_CROSS_ACTIVITY_ERROR);
            return builder;
        }
        return activity.getSyncUserData(userId,userPatronsInfos,serverId);
    }

    /**
     * 摇骰子
     * @param activityId
     * @param userId
     * @param groupId
     * @param usePower
     * @return
     */
    public static LangYaBangProto.LangYaRollDiceRespMsg.Builder rollDice(int activityId,long userId,int groupId,int usePower){
        LangYaBangProto.LangYaRollDiceRespMsg.Builder builder = LangYaBangProto.LangYaRollDiceRespMsg.newBuilder();
        LangYaBangActivity activity = getActivity(activityId, groupId);
        if (activity == null){
            builder.setRet(GameErrorCode.E_LANG_YA_CROSS_ACTIVITY_ERROR);
            return builder;
        }
        return activity.rollDice(userId,usePower);
    }

    /**
     * 代政
     */
    public static LangYaBangProto.DoDaizhengEventRespMsg.Builder daiZheng(int activityId,long userId,int groupId,int chooseBuilding){
        LangYaBangProto.DoDaizhengEventRespMsg.Builder builder = LangYaBangProto.DoDaizhengEventRespMsg.newBuilder();
        LangYaBangActivity activity = getActivity(activityId, groupId);
        if (activity == null){
            builder.setRet(GameErrorCode.E_LANG_YA_CROSS_ACTIVITY_ERROR);
            return builder;
        }
        return activity.daiZheng(userId,chooseBuilding);
    }

    /**
     * pve
     */
    public static LangYaBangProto.DoPveEventRespMsg.Builder dealPve(int activityId,long userId,int groupId){
        LangYaBangProto.DoPveEventRespMsg.Builder builder = LangYaBangProto.DoPveEventRespMsg.newBuilder();
        LangYaBangActivity activity = getActivity(activityId, groupId);
        if (activity == null){
            builder.setRet(GameErrorCode.E_LANG_YA_CROSS_ACTIVITY_ERROR);
            return builder;
        }
        return activity.dealPve(userId);
    }


    /**
     * pvp
     */
    public static LangYaBangProto.DoPvpEventRespMsg.Builder dealPvp(int activityId,long userId,int chooseBuildingType,int groupId){
        LangYaBangProto.DoPvpEventRespMsg.Builder builder = LangYaBangProto.DoPvpEventRespMsg.newBuilder();
        LangYaBangActivity activity = getActivity(activityId, groupId);
        if (activity == null){
            builder.setRet(GameErrorCode.E_LANG_YA_CROSS_ACTIVITY_ERROR);
            return builder;
        }
        return activity.dealPvp(userId,chooseBuildingType);
    }

    public static LangYaBangProto.LangYaBangUsePowerItemRespMsg.Builder addPower(int activityId,long userId,int useNum,int groupId){
        LangYaBangProto.LangYaBangUsePowerItemRespMsg.Builder builder = LangYaBangProto.LangYaBangUsePowerItemRespMsg.newBuilder();
        LangYaBangActivity activity = getActivity(activityId, groupId);
        if (activity == null){
            builder.setRet(GameErrorCode.E_LANG_YA_CROSS_ACTIVITY_ERROR);
            return builder;
        }
        return activity.addPower(userId,useNum);
    }

    public static LangYaBangProto.LangYaBangUpgradeBuildingRespMsg.Builder upgradeBuilding (int activityId,long userId,int groupId,int buildingType){
        LangYaBangProto.LangYaBangUpgradeBuildingRespMsg.Builder builder = LangYaBangProto.LangYaBangUpgradeBuildingRespMsg.newBuilder();
        LangYaBangActivity activity = getActivity(activityId, groupId);
        if (activity == null){
            builder.setRet(GameErrorCode.E_LANG_YA_CROSS_ACTIVITY_ERROR);
            return builder;
        }
        return activity.upgradeBuilding(userId,buildingType);
    }

    public static LangYaBangProto.InitiateDeclareWarRespMsg.Builder declareWar(int activityId,long userId,int groupId,String unionUid){
        LangYaBangProto.InitiateDeclareWarRespMsg.Builder builder = LangYaBangProto.InitiateDeclareWarRespMsg.newBuilder();
        LangYaBangActivity activity = getActivity(activityId, groupId);
        if (activity == null){
            builder.setRet(GameErrorCode.E_LANG_YA_CROSS_ACTIVITY_ERROR);
            return builder;
        }
        return activity.declareWar(userId,unionUid);
    }

    public static LangYaBangProto.GetHistorySimpleDeclareWarInfoRespMsg.Builder getHistoryDeclareWarSimple(int activityId,long userId,int groupId){
        LangYaBangProto.GetHistorySimpleDeclareWarInfoRespMsg.Builder builder = LangYaBangProto.GetHistorySimpleDeclareWarInfoRespMsg.newBuilder();
        LangYaBangActivity activity = getActivity(activityId, groupId);
        if (activity == null){
            builder.setRet(GameErrorCode.E_LANG_YA_CROSS_ACTIVITY_ERROR);
            return builder;
        }
        return activity.getHistoryDeclareWarSimple(userId);
    }

    public static LangYaBangProto.GetHistoryDeclareWarDetailInfoRespMsg.Builder getHistoryDeclareWarDetail(int activityId,long userId,int groupId,int declareWarUid,String belongUnionUid){
        LangYaBangProto.GetHistoryDeclareWarDetailInfoRespMsg.Builder builder = LangYaBangProto.GetHistoryDeclareWarDetailInfoRespMsg.newBuilder();
        LangYaBangActivity activity = getActivity(activityId, groupId);
        if (activity == null){
            builder.setRet(GameErrorCode.E_LANG_YA_CROSS_ACTIVITY_ERROR);
            return builder;
        }
        return activity.getHistoryDeclareWarDetail(userId,declareWarUid,belongUnionUid);
    }

    public static LangYaBangProto.GetLangYaDeclareWarUnionListResp.Builder getCanDeclareWarUnionAndRank(int activityId,int groupId,long userId,int pageNo,int pageSize){
        LangYaBangProto.GetLangYaDeclareWarUnionListResp.Builder respBuilder = LangYaBangProto.GetLangYaDeclareWarUnionListResp.newBuilder();

        LangYaBangActivity activity = getActivity(activityId, groupId);
        if (activity == null){
            respBuilder.setRet(GameErrorCode.E_LANG_YA_CROSS_ACTIVITY_ERROR);
            return respBuilder;
        }

        respBuilder.setRet(0);

        List<UnionYRank> rankList = CrossYRankMgr.getSortUnionRankListByPagePara(activityId, groupId, String.valueOf(eGamePlayerEventType.LangYaUnionScoreRank.getValue()),pageNo,pageSize);
        int rankNum = CrossYRankMgr.getUnionRankNum(rankList, userId);
        int maxListSize = CrossYRankMgr.getSortUnionRankListMaxNum(activityId, groupId, String.valueOf(eGamePlayerEventType.LangYaUnionScoreRank.getValue()));
        UnionYRank unionYRank = CrossYRankMgr.getUnionYRank(activityId, groupId, String.valueOf(eGamePlayerEventType.LangYaUnionScoreRank.getValue()), userId);

        CrossActivityProto.CrossActivityUnionRankListMsg.Builder rankBuilder = CrossActivityProto.CrossActivityUnionRankListMsg.newBuilder();
        rankBuilder.setActivityId(activityId);
        for (UnionYRank rank : rankList) {
            rankBuilder.addRankList(CrossActivityProto.CrossActivityUnionRankTempMsg.newBuilder()
                    .setUnionUid(rank.getUnionUid())
                    .setUnionBaseData(UnionBasePb.parseUnionBaseTempMsg(rank.getUnionBaseInfo()))
                    .setValue(rank.getValue().toString())
            );
        }

        CrossActivityProto.CrossActivityUnionRankListRespMsg.Builder builder = CrossActivityProto.CrossActivityUnionRankListRespMsg.newBuilder();
        builder.setActivityId(activityId);
        builder.setMyRank(rankNum);
        builder.setValue(unionYRank == null ? "0" : unionYRank.getValue().toString());
        builder.setRankList(rankBuilder);

        respBuilder.setRankMsg(builder);
        respBuilder.setMaxRankNum(maxListSize);
        if (unionYRank != null){
            Map<String, Integer> hateMap = activity.getHateMap(unionYRank.getUnionUid());
            if (hateMap!=null){
                for (Map.Entry<String, Integer>entry :hateMap.entrySet()){
                    LangYaBangProto.OtherHateValue.Builder hateBuilder = LangYaBangProto.OtherHateValue.newBuilder();
                    hateBuilder.setUnionUid(entry.getKey());
                    hateBuilder.setHaveValue(entry.getValue());
                    respBuilder.addOtherHateValue(hateBuilder);
                }
            }
        }
        return respBuilder;
    }

    public static LangYaBangProto.ChooseDeclareWarBattleUserResp.Builder chooseDeclareWarBattleUser(int activityId,int groupId,long userId,int declareUid,long enemyUserId){
        LangYaBangProto.ChooseDeclareWarBattleUserResp.Builder builder =  LangYaBangProto.ChooseDeclareWarBattleUserResp.newBuilder();
        LangYaBangActivity activity = getActivity(activityId, groupId);
        if (activity == null){
            builder.setRet(GameErrorCode.E_LANG_YA_CROSS_ACTIVITY_ERROR);
            return builder;
        }

        return activity.chooseDeclareWarBattleUser(userId,enemyUserId,declareUid);
    }

    public static LangYaBangProto.LangYaGetOtherHelpRewardRespMsg.Builder getOtherHelpReward(int activityId,int groupId,long userId){
        LangYaBangProto.LangYaGetOtherHelpRewardRespMsg.Builder builder =LangYaBangProto.LangYaGetOtherHelpRewardRespMsg.newBuilder();
        LangYaBangActivity activity = getActivity(activityId, groupId);
        if (activity == null){
            builder.setRet(GameErrorCode.E_LANG_YA_CROSS_ACTIVITY_ERROR);
            return builder;
        }
        return activity.getOtherHelpReward(userId);
    }

    public static LangYaBangProto.LangYaGetDeclareWarAllNoticeRespMsg.Builder getAllNoticeData(int activityId,int groupId){
        LangYaBangProto.LangYaGetDeclareWarAllNoticeRespMsg.Builder builder = LangYaBangProto.LangYaGetDeclareWarAllNoticeRespMsg.newBuilder();
        LangYaBangActivity activity = getActivity(activityId, groupId);
        if (activity == null){
            builder.setRet(GameErrorCode.E_LANG_YA_CROSS_ACTIVITY_ERROR);
            return builder;
        }
        return activity.getAllDeclareWarNotice();

    }

    public static LangYaBangProto.LangYaBangGetNoOverDeclareWarListRespMsg.Builder getNoEndDeclareWar(int activityId,int groupId,long userId){
        LangYaBangProto.LangYaBangGetNoOverDeclareWarListRespMsg.Builder builder =LangYaBangProto.LangYaBangGetNoOverDeclareWarListRespMsg.newBuilder();
        LangYaBangActivity activity = getActivity(activityId, groupId);
        if (activity == null){
            builder.setRet(GameErrorCode.E_LANG_YA_CROSS_ACTIVITY_ERROR);
            return builder;
        }
        return activity.getNoEndDeclareWar(userId);

    }

    public static LangYaBangProto.LangYaBangSetAutoSwitchRespMsg.Builder updateAutoSwitch(int activityId,int groupId,long userId,List<Integer> autoSwitchList){
        LangYaBangProto.LangYaBangSetAutoSwitchRespMsg.Builder builder =LangYaBangProto.LangYaBangSetAutoSwitchRespMsg.newBuilder();
        LangYaBangActivity activity = getActivity(activityId, groupId);
        if (activity == null){
            builder.setRet(GameErrorCode.E_LANG_YA_CROSS_ACTIVITY_ERROR);
            return builder;
        }
        return activity.updateAutoSwitch(userId,autoSwitchList);
    }




    @Override
    public boolean removeExpireData() throws Exception {
        List<Integer> acList = new ArrayList<>();
        long nowTime = System.currentTimeMillis();
        for (CrossLangYaBangActivityGroup activityGroup :activityMap.values()){
            ActivityInfo activityInfo = activityGroup.getActivityInfo();
            if((nowTime > activityInfo.getEndShowTime()  * 1000 +  DateHelper.HOUR_MILLIONS)){
                acList.add(activityInfo.getActivityId());
            }
        }
        for(Integer activityId : acList){
            activityMap.remove(activityId);
        }
        return true;
    }
}
